/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.riq.entity.Coordinate;
import com.riq.entity.Department;
import com.riq.entity.Location;
import com.riq.entity.Member;

public class LatitudeServlet extends HttpServlet {
  private static final Logger log = Logger.getLogger(LatitudeServlet.class.getName());
  
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    
//    log.info("Inside Latitude doGet");
    PersistenceManager pm = PMF.get().getPersistenceManager();
    String queryDepartments = " select from " + Department.class.getName() +
                              " where trackingFlag == 'yes' ";
    List<Department> departments = (List<Department>) pm.newQuery(queryDepartments).execute();
    log.info("Departments qty: " + departments.size());
    
    Map geocodeResults = null;
    String latCm = "";
    String lngCm = "";
    String latTm = "";
    String lngTm = "";
    String timestampCm = "";
    String accuracyMetersCm = "";
    
    for (Department d : departments) {
      long tempRangeA = d.getdistGroupA();
      long tempRangeB = d.getdistGroupB();
      long tempRangeC = d.getdistGroupC();
      long distMaxAgeMinutes = d.getdistMaxAge();
      
      // update coordinates for all Members with Latitude Ids for this Department
      String queryMembers =   "select from " + Member.class.getName() + 
      " where deptId == " + d.getid() + " && latitudeId != null ";
      List<Member> members = (List<Member>) pm.newQuery(queryMembers).execute();
      log.info("Members qty: " + members.size());
      if (members.size() != 0) {
        for (Member m : members) {
          geocodeResults = riqGeocode(d.getid(), m.getid(), "Member");
          if (geocodeResults != null && 
        	  d.getcoordinatesLatitude() > 0.0 && d.getcoordinatesLongitude() > 0.0) {
        	if (geocodeResults.get("timeStamp") != null) {
              latCm = String.valueOf(geocodeResults.get("lat"));
              lngCm = String.valueOf(geocodeResults.get("lng"));
              timestampCm = String.valueOf(geocodeResults.get("timeStamp"));
              accuracyMetersCm = String.valueOf(geocodeResults.get("accuracyMeters"));
              m.setdistTimeStamp(Long.valueOf(timestampCm));
              m.setgpsAccuracy(accuracyMetersCm);
              
              // find target coordinates for this Member
              Long targetObjectId = m.gettargetObjectId();
              if (targetObjectId != null) {
                // TODO johnreilly - based on target location lat lng
                Location l = pm.getObjectById(Location.class, targetObjectId);
                latTm = String.valueOf(l.getlastLat());
                lngTm = String.valueOf(l.getlastLng());
              } else {
                latTm =  String.valueOf(d.getcoordinatesLatitude()); 
                lngTm =  String.valueOf(d.getcoordinatesLongitude());
              }
         }
          
          Long distMaxAgeSeconds;
          Map<String, Double> duraResults = riqDuration(d.getid(), m.getid(), "Member", 
                  m.getlatitudeId(), m.gettargetObjectId(), latCm, lngCm, latTm, lngTm);
          
          // calculate the distance group using dept's range & "freshness" variables
          Double minutesAway = duraResults.get("duraValue");
          log.info("minutesAway: " + m.getlastName() + " --- " + minutesAway);
          if (minutesAway!=null){
            m.setdistance(minutesAway);
  
            if (minutesAway < tempRangeA && 
               (distMaxAgeMinutes < (System.currentTimeMillis() - Long.valueOf(timestampCm)) * 60)
                    ) {
              m.setdistGroup("001");
  
            } else if (minutesAway < tempRangeB &&
               (distMaxAgeMinutes < (System.currentTimeMillis() - Long.valueOf(timestampCm)) * 60)
                      ) {
              m.setdistGroup("002");
  
            } else if (minutesAway < tempRangeC &&
               (distMaxAgeMinutes < (System.currentTimeMillis() - Long.valueOf(timestampCm)) * 60)
                        ) {
              m.setdistGroup("003");
  
            } else if (minutesAway >= tempRangeC &&
                (distMaxAgeMinutes < (System.currentTimeMillis() - Long.valueOf(timestampCm)) * 60)
                      ) {
              m.setdistGroup("004");
  
            } else {
              m.setdistGroup("000");
  
            }
          
          pm.makePersistent(m);
          } // if minutes away
        } // if geocode
      } // for Members
    } // if Members
      
      String latCl = "";
      String lngCl = "";
      String latTl = "";
      String lngTl = "";
//      String timestampCl = "";
//      String accuracyMetersCl = "";
      
      // update coordinates for all Locations with LatitudeIds for this Department
      String queryLocations =   "select from " + Location.class.getName() + 
      " where deptId == " + d.getid() + " && latitudeId != '' ";
      List<Location> locations = (List<Location>) pm.newQuery(queryLocations).execute();
      log.info("Locations qty: " + locations.size());
      if (locations.size() != 0) {
        for (Location l : locations) {
          geocodeResults = riqGeocode(d.getid(), l.getid(), "Location");
          
          // only get Duration for Location driving to Target if there is an Active Alert
          latCl = String.valueOf(geocodeResults.get("lat"));
          lngCl = String.valueOf(geocodeResults.get("lng"));
          
          // find target coordinates for this Location
          latTl = String.valueOf(d.getcoordinatesLatitude());
          lngTl = String.valueOf(d.getcoordinatesLongitude());
          
          if (latTl != null && lngTl != null) {
          Map<String, Double> duraResults = riqDuration(d.getid(), l.getid(), "Location", 
                  l.getlatitudeId(), l.gettargetObjectId(), latCl, lngCl, latTl, lngTl);
          }
          
          // no return since riqDuration creates the Coordinate record with required info

     	}
      }
    } // for Departments
    
      pm.close(); 
  
  }
  
  
  // GEOCODE
    
  private Map<String, String> riqGeocode(
          Long deptId, 
//          Long alertId, 
          Long objectId, 
          String objectType) {
    
//    log.info("");
//    log.info("Inside riqGeocode");
//    log.info("ObjectType: " + objectType);
//    log.info("ObjectId: " + objectId.toString());

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Map<String, String> latlngMap = new HashMap();    
    
    Member m = null;
    Location l = null;
    String latitudeId = "";

    if ("Member".equalsIgnoreCase(objectType)) {
      try {
	      m = (Member) pm.getObjectById(Member.class, objectId);
	      log.info("Member Last Name: " + m.getlastName());
	      latitudeId = m.getlatitudeId();
	      } catch (javax.jdo.JDOObjectNotFoundException mi) {
	      }
  	} else if ("Location".equalsIgnoreCase(objectType)) {
  	  try {
  	      l = (Location) pm.getObjectById(Location.class, objectId);
  	      latitudeId = l.getlatitudeId();
  	      } catch (javax.jdo.JDOObjectNotFoundException mi) {
  	      }
  	} else {
  	      return null;
  	}
    
    String geocodeURL =  "http://www.google.com/latitude/apps/badge/api?user=" + 
                          latitudeId.trim() + "&type=json";
  
    try {
      
      URL url;
      Long gpsTimeStamp = null;
      String gpsAccuracy = "";
   
      url = new URL(geocodeURL);
      BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
      StringBuilder tempString = new StringBuilder();
      String line;
      
      while ((line=reader.readLine())!=null) {
        tempString.append(line);
      }
      
      JSONObject obj = new JSONObject(tempString.toString());
      
//      if ("FeatureCollection".equalsIgnoreCase(obj.getString("type"))) {
        JSONArray features = obj.getJSONArray("features");
//        log.info("Just before Feature not null check inside geocode method");
//        log.info("Geometry Position in tempString: " + tempString.indexOf("geometry"));

        if (tempString.indexOf("geometry") < 10) {
          
          return (null);
          
        } else {
          
          JSONObject feature = features.getJSONObject(0);
          JSONObject geometry = feature.getJSONObject("geometry");
          JSONArray coordinates = geometry.getJSONArray("coordinates");
          Double lat = (Double) coordinates.get(0);
          Double lng = (Double) coordinates.get(1);
          
          JSONObject properties = feature.getJSONObject("properties");
          gpsTimeStamp = properties.getLong("timeStamp");
          gpsAccuracy = String.valueOf(properties.getLong("accuracyInMeters"));
              
//          log.info("gLat: " + lat);
//          log.info("gLng: " + lng);
//          log.info("gTimeStamp: " + gpsTimeStamp);  
//          log.info("gAccuracy in Meters: " + gpsAccuracy);
//          log.info("gLatitudeId: " + latitudeId.trim());
          
          latlngMap.put("lat", String.valueOf(lat));
          latlngMap.put("lng", String.valueOf(lng));
          latlngMap.put("timeStamp", gpsTimeStamp.toString());
          latlngMap.put("accuracyMeters", gpsAccuracy.toString());

          Coordinate c = new Coordinate (
                  deptId,
//                  alertId,
                  objectId,
                  objectType,
                  latitudeId,
                  System.currentTimeMillis(), 
                  gpsTimeStamp,
                  lat,
                  lng,
                  gpsAccuracy,
                  "dist",
                  null
                  );
          pm.makePersistent(c);      
        }       
//      }
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
  
    return (latlngMap);
  }
  
  
  
  
  
  
// DURATION  
  
 private Map<String, Double> riqDuration(Long deptId, Long objectId, String objectType,
         String latitudeId, Long targetObjectId, 
         String lat1, String lng1, String lat2, String lng2) {
   
//   log.info("");
//   log.info("Inside riqDuration");
    
   PersistenceManager pm = PMF.get().getPersistenceManager();
   Map<String, Double> duraMap = new HashMap();    
   String directionsURL =  "http://maps.googleapis.com/maps/api/directions/json?origin=" +
  		lng1 + "," + lat1 + "&destination=" + lat2 + "," + lng2 + "&sensor=false";
  
//    log.info("dURL: " + directionsURL);
    try {
      
      URL url;
      url = new URL(directionsURL);
      BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
      StringBuilder tempString = new StringBuilder();
      String line;
      
      while ((line=reader.readLine())!=null) {
        tempString.append(line);
      }
      
      JSONObject obj = new JSONObject(tempString.toString());
      if ("ok".equalsIgnoreCase(obj.getString("status"))) {
        JSONArray routes = obj.getJSONArray("routes");
        if (routes.length() > 0) {
          JSONObject route = routes.getJSONObject(0);
          JSONArray legs = route.getJSONArray("legs");
          JSONObject duration = legs.getJSONObject(0).getJSONObject("duration");
          JSONObject distance = legs.getJSONObject(0).getJSONObject("distance");
          Double start_lat = legs.getJSONObject(0).getJSONObject("start_location").getDouble("lat");
          Double start_lng = legs.getJSONObject(0).getJSONObject("start_location").getDouble("lng");
          
//          log.info("start_lat: " + start_lat);
//          log.info("start_lng: " + start_lng);
//          log.info("end_lng: " + lat2);
//          log.info("end_lng: " + lng2);

          Double duraValue = Double.valueOf(duration.getDouble("value"))/60;
          Double distValue = Double.valueOf(distance.getLong("value"));
          
//          log.info("duraValueDouble: " + duraValue);
//          log.info("distValueDouble: " + distValue);
          
          duraMap.put("duraValue", duraValue);
          duraMap.put("distValue", distValue);
          
          Coordinate c = new Coordinate (
                  deptId,
//                  alertId,
                  objectId,
                  objectType,
                  latitudeId,
                  System.currentTimeMillis(), 
                  System.currentTimeMillis(),
                  start_lat,
                  start_lng,
                  "not applicable",
                  "dura",
                  targetObjectId
                  );
          pm.makePersistent(c);   
        }       
      }
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    return (duraMap);
  }
  
 
 
}
  

